﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Microsoft.AspNetCore.Mvc;
using WqLunTan.Filters;
using WqLunTan.Models.DataBase;

namespace WqLunTan.Areas.Manage.Controllers
{
    /// <summary>
    /// 网站的头部广告位内容设置
    /// </summary>
    [Auth(AuthType = WqUserAuth.Manage)]
    public class HeaderContentController : BaseManageController
    {
        /// <summary>
        /// 选项卡显示的详情页
        /// </summary>
        /// <returns></returns>
        public IActionResult Deatil()
        {
            var list = DbContext.SiteHeader.ToList();
            ViewData["list"] = list;
            if (list.Count > 0)
            {
                var uids = list.Select(x => x.uid).ToList();
                var users = DbContext.Users.Where(x => uids.Contains(x.Id)).ToList();
                ViewData["users"] = users;
            }
            else
            {
                ViewData["users"] = new List<WqUser>();
            }
            return View();
        }

        /// <summary>
        /// 更新网站广告位的内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IActionResult Update(site_layout_content model)
        {
            if (!string.IsNullOrWhiteSpace(model.content))
            {
                var data = DbContext.SiteHeader.Where(x => x.position == model.position).SingleOrDefault();

                if (data != null)
                {
                    if (data.id != model.id)
                    {
                        return JsonFailureResult("数据异常,操作失败");
                    }

                    data.content = model.content;
                    data.uid = LoginUser.Id;
                    data.last_update = DateTimeOffset.UtcNow;
                    if (data.content.EndsWith("<p><br></p>"))
                    {
                        data.content = data.content.Replace("<p><br></p>", "");
                    }
                }
                else
                {
                    data = new site_layout_content();
                    data.uid = LoginUser.Id;
                    data.content = model.content;
                    data.create_time = DateTimeOffset.UtcNow;
                    data.last_update = DateTimeOffset.UtcNow;
                    data.position = model.position;
                    if (data.content.EndsWith("<p><br></p>"))
                    {
                        data.content = data.content.Replace("<p><br></p>", "");
                    }

                    DbContext.SiteHeader.Add(data);
                }

                DbContext.SaveChanges();
                httpCacheHelper.RemoveCacheByKey("site_header_list_layout");
            }

            return JsonOkResult("保存成功");
        }
    }
}